package ThreeDayMoreThread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    //1.创建锁对象
    private Lock lock=new ReentrantLock();
    //2.创建共享的数据
    private int add=0;
    //3.处理数据的方法
    public void addSum(){
        lock.lock();
        try {
            add++;
        } finally {
            lock.unlock();
        }
    }
    public int getAdd(){
       return add;
    }

    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        //使用多线程模拟并发操作 创建20个线程
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    testLock.addSum();
                }
            }).start();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("所以线程的计算结果："+testLock.getAdd());
    }
}
